package edu.ubb.remeye.communication.message.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import edu.ubb.remeye.communication.MessageType;
import edu.ubb.remeye.communication.message.Message;

/**
 * Message decoder class.
 * 
 * @author Andrew Ianicicau
 *
 */
public class MessageDecoder extends CumulativeProtocolDecoder {
	
	///////////////////////////////////////////////////////////////////////////////////
	////		METHODS - MessageDecoder
	///////////////////////////////////////////////////////////////////////////////////
	
	/**
	 * Reconstructing the Message object from received bytes.
	 */
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		if(in.prefixedDataAvailable(4)) {		
			int length = in.getInt();
			
			Message message = new Message();
			MessageType type = MessageType.getMessageType(in.get());
			message.setMessageType(type);
			
			byte[] messageBytes = new byte[length-1];
			in.get(messageBytes);
			message.setMessage(messageBytes);
			
			out.write(message);
			return true;
		} else {
			return false;
		}
	}

}
